package com.bluetoothprint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.bluetoothprint.BluetoothControler.BluetoothPrintListener;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ht380d4G_jar_demo.R;

public class BlueToothActivity extends Activity implements OnClickListener,
		BluetoothPrintListener {
	private BluetoothAdapter blueAdapter;
	private TextView noticeTv;
	private Button searchBtn, printBtn, clearBtn;
	private Spinner sp;
	private EditText printEt;
	private List<String> deviceList;
	// private BluetoothService blueService;
	private BluetoothControler blueCon;
	private HashMap<String, BluetoothDevice> mapDevice;
	private BluetoothBrocast bluetoothBrocast;
	private boolean isConnecting;
	private String address;
	private int preIndex;
	private int currentState;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				if (deviceList != null && deviceList.size() > 0) {
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							BlueToothActivity.this,
							android.R.layout.simple_spinner_item, deviceList);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					sp.setAdapter(adapter);
					if(preIndex < deviceList.size()){
						sp.setSelection(preIndex);
					}
				}
				break;
			case 1:
				if (noticeTv != null) {
					String notice = (String) msg.obj;
					System.out.println("Msg:" + notice);
					noticeTv.setText("");
					noticeTv.setText(notice);
					noticeTv.invalidate();
				}
				break;

			default:
				break;
			}
		};
	};

	private class BluetoothBrocast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				noticeTv.setText(getString(R.string.bluetooth_searching));
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				// noticeTv.setText("搜索完成");
			} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				blueAdapter.cancelDiscovery();
				// initDeviceListInThread();
			} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {

			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetooth_printer);
		blueCon = BluetoothControler.getInstance(this, this);
		bluetoothBrocast = new BluetoothBrocast();
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(bluetoothBrocast, filter);
		initViews();
		if (checkBlueAvailable()) {
			initDeviceListInThread();

		}
		currentState = BluetoothService.STATE_NONE;
	}

	private void initDeviceListInThread() {
		new Thread() {
			public void run() {
				blueAdapter.cancelDiscovery();
				if (blueCon != null)
					blueCon.disConnect();
				Set<BluetoothDevice> deviceSet = blueAdapter.getBondedDevices();
				if (deviceSet != null && deviceSet.size() > 0) {
					if (deviceList == null)
						deviceList = new ArrayList<String>();
					if (mapDevice == null)
						mapDevice = new HashMap<String, BluetoothDevice>();
					if (deviceList != null && deviceList.size() > 0) {
						preIndex = 0;
						deviceList.clear();
					}
					if (mapDevice != null && mapDevice.size() > 0) {
						mapDevice.clear();
					}
					int i = 0;
					for (BluetoothDevice device : deviceSet) {
						String key = device.getName() + ":"
								+ device.getAddress();
						deviceList.add(key);
						mapDevice.put(key, device);
						address = Preference
								.getLastDeviceAddress(BlueToothActivity.this);
						if (device.getAddress().equals(address)) {
							preIndex = i;
							System.out.println("preIndex:" + preIndex);
						}
						i++;
					}
					mHandler.sendEmptyMessage(0);

				}
			};
		}.start();

	}

	private void initViews() {
		// TODO Auto-generated method stub
		sp = (Spinner) findViewById(R.id.bluetooth_printer_sp);
		searchBtn = (Button) findViewById(R.id.bluetooth_printer_search_btn);
		printBtn = (Button) findViewById(R.id.bluetooth_printer_print_btn);
		clearBtn = (Button) findViewById(R.id.bluetooth_printer_clear_btn);
		searchBtn.setOnClickListener(this);
		printBtn.setOnClickListener(this);
		clearBtn.setOnClickListener(this);
		noticeTv = (TextView) findViewById(R.id.bluetooth_printertest_notice_tv);
		printEt = (EditText) findViewById(R.id.bluetooth_printer_et);
		sp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				System.out.println("position:" + position);
				BluetoothDevice device = mapDevice.get((String) sp
						.getSelectedItem());
				if (device != null) {

					if (blueCon != null) {
						blueAdapter.startDiscovery();
						blueCon.disConnect();
						try {
							System.out.println("sleep_start");
							Thread.sleep(500);
							System.out.println("sleep_end");
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						blueAdapter.cancelDiscovery();
						noticeTv.setText(getString(R.string.bluetooth_connectingto)
								+ device.getName()
								+ ":"
								+ device.getAddress()
								+ "...");
						blueCon.connect(device);
						isConnecting = true;
					}
					// if (!isConnecting) {
					// System.out.println("onItemSelected");
					//
					// if (blueCon != null) {
					// noticeTv.setText("正在连接到:" + device.getName() + ":"
					// + device.getAddress() + "...");
					// blueCon.connect(device);
					// isConnecting = true;
					// }
					//
					// }

				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(BlueToothActivity.this, "onNothingSelected",
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public boolean checkBlueAvailable() {
		blueAdapter = BluetoothAdapter.getDefaultAdapter();
		if (blueAdapter == null) {
			Toast.makeText(this, getString(R.string.bluetooth_nodevice),
					Toast.LENGTH_SHORT).show();
			finish();
			return false;
		}
		if (blueAdapter.getState() == BluetoothAdapter.STATE_OFF
				|| blueAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
			Toast.makeText(this, getString(R.string.bluetooth_opendevice),
					Toast.LENGTH_SHORT).show();
			startActivityForResult(new Intent(
					Settings.ACTION_BLUETOOTH_SETTINGS), 200);
			return false;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (blueAdapter != null)
			blueAdapter.cancelDiscovery();
		if (blueCon != null)
			blueCon.destroy();
		unregisterReceiver(bluetoothBrocast);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 200) {
			System.out.println("onActivityResult");
			if (checkBlueAvailable()) {

				initDeviceListInThread();
				System.out.println("initDeviceListInThread");
			}

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bluetooth_printer_clear_btn:
			if (checkBlueAvailable()) {
				initDeviceListInThread();

			}
			// if (blueCon != null)
			// blueCon.disConnect();
			// blueCon = BluetoothControler.getInstance(this, this);
			// BluetoothDevice device = mapDevice.get((String) sp
			// .getSelectedItem());
			// if (device != null) {
			// if (!isConnecting) {
			// System.out.println("onItemSelected");
			//
			// if (blueCon != null) {
			// noticeTv.setText("正在连接到:" + device.getName() + ":"
			// + device.getAddress() + "...");
			// blueCon.connect(device);
			// isConnecting = true;
			// }
			//
			// }
			//
			// }
			break;
		case R.id.bluetooth_printer_print_btn:
			System.out.println("print");
			final String content = printEt.getText().toString();
			if (content != null && content.length() > 0) {
				new Thread() {
					public void run() {
						if (blueCon != null) {
							try {
								blueCon.write(content.getBytes("GB2312"));
								blueCon.write("\r\n\r\n\r\n".getBytes("GB2312"));
							} catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
							}
						}

					};
				}.start();
			}

			break;
		case R.id.bluetooth_printer_search_btn:
			if (blueAdapter != null)
				blueAdapter.cancelDiscovery();
			if (blueCon != null) {
				blueCon.disConnect();
			}
			startActivityForResult(new Intent(
					Settings.ACTION_BLUETOOTH_SETTINGS), 200);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onStateChange(int currentState) {
		// TODO Auto-generated method stub
		switch (currentState) {
		case BluetoothService.STATE_CONNECTED:
			currentState = BluetoothService.STATE_CONNECTED;
			isConnecting = false;
			break;
		case BluetoothService.STATE_CONNECTING:
			currentState = BluetoothService.STATE_CONNECTING;
			isConnecting = true;
			break;
		case BluetoothService.STATE_LISTEN:
			currentState = BluetoothService.STATE_LISTEN;
			break;
		case BluetoothService.STATE_NONE:
			currentState = BluetoothService.STATE_NONE;
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public boolean onConnected(String deviceName, String address) {
		// TODO Auto-generated method stub
		isConnecting = false;
		mHandler.sendMessage(mHandler.obtainMessage(1,
				getString(R.string.bluetooth_connect_success) + deviceName
						+ ":" + address));
		Preference.setLastDeviceAddress(this, address);
		System.out.println("address:" + address);
		return true;
	}

	@Override
	public boolean onConnectFailed() {
		// TODO Auto-generated method stub
		isConnecting = false;
		System.out.println("sendMessage:连接失败");
		mHandler.sendMessage(mHandler.obtainMessage(1,
				getString(R.string.bluetooth_connect_failed)));
		return true;
	}

	@Override
	public boolean onConnectedBroken() {
		// TODO Auto-generated method stub
		isConnecting = false;
		mHandler.sendMessage(mHandler.obtainMessage(1,
				getString(R.string.bluetooth_connection_broken)));
		return true;
	}

}
